#include "fileselectdlg.h"
#include "ui_fileselectdlg.h"

fileSelectDlg::fileSelectDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::fileSelectDlg)
{
    ui->setupUi(this);
    setWindowTitle("选择文件");

    QFont ft;
    ft.setPointSize(16);
    ui->fileSelectLabel->setFont(ft);
    ui->listWidget->setFont(ft);

    QIcon up(QIcon(":/res/res/up.png"));
    ui->upBtn->setIcon(up);
    ui->okBtn->setEnabled(false);
    ui->upBtn->setEnabled(false);
    ui->addBtn->setEnabled(false);
    ui->rmvBtn->setEnabled(false);
    ui->nextBtn->setEnabled(false);
    ui->prevBtn->setEnabled(false);

    connect(this,
            SIGNAL(checkFile()),
            this,
            SLOT(processCheckFile()));
}

fileSelectDlg::~fileSelectDlg()
{
    delete ui;
    qDebug() << "deleted";
}

//void fileSelectDlg::check()
//{
////    ui->welcomeLabel->setText("欢迎您，" + loginName);

//    if(hostAddr.isNull() | (port == 0)){
//        QMessageBox::warning(this, "警告", "没有获取到IP地址，请手动设置", QMessageBox::Ok);
//        IPSetDlg *ipSet = new IPSetDlg();
//        ipSet->setAttribute(Qt::WA_DeleteOnClose);
//        connect(ipSet,
//                SIGNAL(IPChanged(QHostAddress, unsigned short)),
//                this,
//                SLOT(setIPAndPort(QHostAddress, unsigned short)));
//        ipSet->exec();
//        modifyDb();
////        qDebug() << hostAddr << port << userId;
////        qDebug() << hostAddr << " ---------------------- " << port;
//    }
//    connectToServer();
//}

void fileSelectDlg::connectToServer()
{
    ftp = new QFtp(this);

    //对每一个信号进行响应
    connect(ftp, SIGNAL(listInfo(QUrlInfo)),
            this, SLOT(getVideoList(QUrlInfo)));
    //链接FTP命令完成后的操作
    connect(ftp, SIGNAL(commandFinished(int,bool)),
            this, SLOT(ftpCommandFinished(int,bool)));

    connect(ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
            this, SLOT(updateDataTransferProgress(qint64,qint64)));

    ftp->connectToHost(hostAddr, port);
    ftp->login("anonymous", "");

    ui->pathLabel->setText(targetProject.getUrl());
}

void fileSelectDlg::getVideoList(const QUrlInfo &i)
{
    isDir[fromFtpEncoding(i.name())] = i.isDir();
//    ui->listWidget->addItem(fromFtpEncoding(i.name()));
    videoList.append(fromFtpEncoding(i.name()));
//    qDebug() << videoList;
}

void fileSelectDlg::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Escape)
        event->ignore();
}

void fileSelectDlg::closeEvent(QCloseEvent *event)
{
    if(canQuit){
        this->accept();
        return ;
    }

    else if(fileName.isEmpty()){
        if (ftp == nullptr) {
            this->accept();
            return ;
        }
        QMessageBox::warning(this, "警告", "没有选择文件，即将返回登陆界面！", QMessageBox::Ok);
        logger.writeLog(Logger::LogoutSuccessfully);

        loginDlg *dlg = new loginDlg();
        this->accept();

        dlg->setAttribute(Qt::WA_DeleteOnClose);
        dlg->exec();
    }
    else if(ftp != nullptr){
        event->ignore();
    }
}

void fileSelectDlg::updateDataTransferProgress(qint64 readBytes, qint64 totalBytes)
{
    downloadProgressDlg->setMaximum(totalBytes);
    downloadProgressDlg->setValue(readBytes);
}

void fileSelectDlg::on_okBtn_clicked()
{
    selectQueue.clear();

    for(int i = 0; i < ui->downloadListWidget->count(); ++i){
        if(!QFile::exists(ui->downloadListWidget->item(i)->text()))
            selectQueue.append(ui->downloadListWidget->item(i)->text());

//        for(int j = 0;j < ui->listWidget->count(); ++j){
//            qDebug() << ui->listWidget->item(j)->text() << "?" << ui->downloadListWidget->item(i)->text();
//            if(ui->listWidget->item(j)->text().endsWith(".txt")
//                    && ui->listWidget->item(j)->text().left(ui->listWidget->item(j)->text().lastIndexOf("."))
//                    == ui->downloadListWidget->item(i)->text().left(ui->downloadListWidget->item(i)->text().lastIndexOf(".")))
//                selectQueue.append(ui->listWidget->item(j)->text());
//        }
//        else {
//            QMessageBox::information(this, "信息", "文件存在", QMessageBox::Ok);
//        }
        playQueue.append(ui->downloadListWidget->item(i)->text());
    }
    playQueue.sort();//对乱序的播放列表进行排序，否则BOM表读的数据会混乱，问题已解决。

    //由于BOM表单是追加下载，所以一定在队列最末尾。
    BomFileSelect *t_file_select = new BomFileSelect();
    QStringList t_list;

    for(int i = 0; i < ui->listWidget->count(); ++i){
        if(ui->listWidget->item(i)->text().endsWith(".txt"))
        {
            t_list.append(ui->listWidget->item(i)->text());
        }
    }

    t_file_select->f_setList(t_list);
    int code = t_file_select->exec();

    if(code)
    {
        qDebug() << t_file_select->f_getFileName();
    }
    delete t_file_select;
//    for(int i = 0; i < ui->listWidget->count(); ++i){
//        qDebug() << currentPath << "------------" << ui->listWidget->item(i)->text();
//        if(currentPath.contains(ui->listWidget->item(i)->text()
//                                .left(ui->listWidget->item(i)->text()
//                                      .lastIndexOf(".")))
//                && ui->listWidget->item(i)->text().endsWith(".txt")){
//                selectQueue.append(ui->listWidget->item(i)->text());
//            qDebug() << selectQueue;
//        }
//    }
    downloadVideoAndBOM();
}

//将FTP的UTF-16编码格式转换成系统支持的格式
QString fileSelectDlg::fromFtpEncoding(const QString str)
{
#ifdef Q_OS_WIN
       return QString::fromLocal8Bit(str.toLatin1());
   #else
       QTextCodec *codec = QTextCodec::codecForName("gbk");
       if (codec) {
           return codec->toUnicode(InputStr.toLatin1());
       } else {
           return QString("");
       }
   #endif
}

//将文件转换成UTF-16格式
QString fileSelectDlg::toFtpEncoding(const QString str)
{
#ifdef Q_OS_WIN
    return QString::fromLatin1(str.toLocal8Bit());
#else
    QTextCodec *codec= QTextCodec::codecForName("gbk");
    if (codec) {
        return QString::fromLatin1(codec->fromUnicode(InputStr));
    } else {
        return QString("");
    }
#endif
}

void fileSelectDlg::callUpMainwindow(QQueue<QString> multiSelectList, QString BOMFile)
{
    //直接传集合进去
    MainWindow *mw = new MainWindow();
    qDebug() << BOMFile << "     in fileSelect";
    mw->setAttribute(Qt::WA_DeleteOnClose);
//    qDebug() << userId << "  " << userName;

    for(int i = 0; i < multiSelectList.count(); ++i){
        multiSelectList[i] = "./" + multiSelectList[i];
//        qDebug() << multiSelectList[i];
    }

    mw->show();

    //mw->playFromFtp(multiSelectList);
    //mw->openBOMFile("./" + BOMFile);
    //mw->buildTreeView();
}

void fileSelectDlg::showList(QStringList videoList, int start)
{
    qDebug() << videoList << "-------is videolist";
    if(!videoList.isEmpty()){
        ui->nextBtn->setEnabled(true);
        ui->prevBtn->setEnabled(true);
        int limit = start + 10;
        for(;start < limit;start++){
            if(start < videoList.size())
                ui->listWidget->addItem(videoList[start]);
            else
                break;
       }
    }
}

//void fileSelectDlg::setHostAndPort(QHostAddress hostAddr, unsigned short port)
//{
//    this->hostAddr = hostAddr;
//    this->port = port;
//}

//void fileSelectDlg::setUserNum(QString id)
//{
//    this->userId = id;
//}

//void fileSelectDlg::setUsername(QString name)
//{
//    this->userName = name;
//}

//bool fileSelectDlg::checkMultiSelect()
//{
//    for(int i = 0;i < ui->listWidget->selectedItems().count(); ++i){
//        if(!isDir.value(ui->listWidget->selectedItems()[i]->text()))
//            continue;
//        else {
//            QMessageBox::critical(this, "错误", "文件组合不能打开", QMessageBox::Ok);
//            return false;
//        }
//    }
//    return true;
//}

void fileSelectDlg::downloadVideoAndBOM()
{
    if (!selectQueue.isEmpty()) {
        fileName = selectQueue.dequeue();
        if(fileName.endsWith(".txt")){
            if(QFile::exists(fileName)){
                QMessageBox::information(this, "提示", "BOM表单文件存在", QMessageBox::Ok);
                if(selectQueue.isEmpty()){
                    BOMFile = fileName;
                    downloadVideoAndBOM();
                    return;//防止代码继续执行弹出下载进度对话框。
                }
            }
            else
                BOMFile = fileName;
        }
        file = new QFile(fileName);
        if (!file->open(QIODevice::WriteOnly)) {
            QMessageBox::information(this, tr("提示"),
                                     tr("无法保存文件 %1: %2.")
                                     .arg(fileName).arg(file->errorString()));
            logger.setFileName(fileName);
            logger.writeLog(Logger::DownloadFaild);
            delete file;
            return;
        }
        ftp->get(toFtpEncoding(fileName), file, QFtp::Binary);

        downloadProgressDlg = new QProgressDialog(this);
        connect(downloadProgressDlg,
                SIGNAL(canceled()),
                this,
                SLOT(cancelDownload()));
        downloadProgressDlg->setLabelText(QString("正在下载%1中").arg(fileName));
        downloadProgressDlg->show();
    }
    else if (!playQueue.isEmpty()) {
        canQuit = true;
        this->close();
        callUpMainwindow(playQueue, BOMFile);
    }
}

//bool fileSelectDlg::modifyDb()
//{
//    //        if(makeConnToDb()){
//            if(db.isOpen()){
//                QSqlQuery query(db);
//                query.exec(QString("update t_usr a"
//                                   " set a.usr_set_ip = '%1',"
//                                   " a.usr_set_port = %2"
//                                   " where a.usr_id = %3").arg(hostAddr).arg(port).arg(userId));
//                query.next();
//                if(!query.isActive()){
//                    QMessageBox::critical(this, "错误", "执行查询失败", QMessageBox::Ok);
//                    return false;
//                }
//                else
//                    return true;
//            }
//    //        }
//            else{
//                QMessageBox::critical(this, "错误", "无法打开数据库", QMessageBox::Ok);
//                return false;
//            }
//}

//bool fileSelectDlg::makeConnToDb()
//{
//        db.setHostName("localhost");
//        db.setPort(3306);
//        db.setUserName("root");
//        db.setPassword("");
//        db.setDatabaseName("test");
//        db.open();

//        if(!db.open()){
//            QMessageBox::critical(this,
//                                  "错误",
//                                  "无法连接到数据库",
//                                  QMessageBox::Ok | QMessageBox::Cancel);
//            logger.writeLog(Logger::DbConnectionFaild);
//            return false;
//        }
//        else {
//            qDebug() << "made conn";
//        }
//        return true;
//}

void fileSelectDlg::ftpCommandFinished(int, bool error)
{

    if (ftp->currentCommand() == QFtp::ConnectToHost) {
        if (error) {
            QMessageBox::information(this, "提示",
                                     QString("未能连接到主机为 %1 的主机，请检查IP地址填写是否正确")
                                     .arg(hostAddr));
            logger.writeLog(Logger::HostConnectionFaild);
            return;
        }
        return;
    }

    if (ftp->currentCommand() == QFtp::Login){
        if(error){
            QMessageBox::critical(this, "错误", "无法登陆至FTP服务器，\n请检查FTP服务器的IP地址、登陆用户名、登陆密码和端口号是否配置正确");
        }
        qDebug() << toFtpEncoding(targetProject.getUrl().mid(targetProject.getUrl().indexOf('\\', 6)));
        ftp->cd(toFtpEncoding(targetProject.getUrl().mid(targetProject.getUrl().indexOf('\\', 6))));
        ftp->list();
    }


    if (ftp->currentCommand() == QFtp::Get) {
        if (error) {
            ftp->abort();
            QMessageBox::critical(this, "错误", QString("无法下载 %1,请删除所有下载项之后重新登陆。")
                                 .arg(fileName), QMessageBox::Ok);
            logger.setFileName(fileName);
            logger.writeLog(Logger::DownloadFaild);
            file->close();
            qDebug() << file->remove();
            delete file;
            return;
        } else {
            QMessageBox::information(this, "提示", QString("已于当前目录中下载 %1")
                                 .arg(file->fileName()));
            logger.setFileName(file->fileName());
            logger.writeLog(Logger::FileOpened);
            downloadProgressDlg->close();
            file->close();
            file->deleteLater();
            downloadVideoAndBOM();

//            callUpMainwindow(file->fileName());

//            canQuit = true;
//            this->close();

        }
    } else if (ftp->currentCommand() == QFtp::List) {
                if(error){
                    QMessageBox::critical(this, "错误", "获取文件信息失败", QMessageBox::Ok);
                    logger.writeLog(Logger::FaildToGetFileInfo);
                }
                else {
                    qDebug() << videoList;
                    showList(this->videoList, 0);
//                    qDebug() << this->isDir;

                }
            }
}

void fileSelectDlg::on_upBtn_clicked()
{
    if(ui->downloadListWidget->count() > 0){
        QMessageBox::warning(this,
                             "警告",
                             "请将右侧列表清空后再进行返回操作。",
                             QMessageBox::Ok);
    }
    else {
        ui->listWidget->clear();
        isDir.clear();
        videoList.clear();
        currentPath = currentPath.left(currentPath.lastIndexOf('/'));

        if (currentPath.isEmpty()) {
            ui->upBtn->setEnabled(false);
            currentPath = "/";
            ftp->cd("/");
        } else {
            ftp->cd(toFtpEncoding(currentPath));
        }

        ui->pathLabel->setText(currentPath);
        ftp->list();
    }
}

void fileSelectDlg::on_cancelBtn_clicked()
{
    QMessageBox::warning(this, "警告", "即将返回登陆界面！", QMessageBox::Ok);
    canQuit = true;
    logger.writeLog(Logger::LogoutSuccessfully);

    loginDlg *dlg = new loginDlg();
    this->close();

    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->exec();
}

void fileSelectDlg::on_nextBtn_clicked()
{
    int i = videoList.indexOf(ui->listWidget->item(0)->text());
    ui->listWidget->clear();
    i + 10 > videoList.size() ? i : i += 10;
    showList(videoList, i);
}

void fileSelectDlg::on_prevBtn_clicked()
{
    int j = videoList.indexOf(ui->listWidget->item(0)->text());
    ui->listWidget->clear();
    j - 10 < 0 ? j = 0: j -= 10;
    showList(videoList, j);

}

void fileSelectDlg::on_addBtn_clicked()
{
    if(ui->listWidget->currentItem()->text().endsWith(".mp4")
            || ui->listWidget->currentItem()->text().endsWith(".flv")
            || ui->listWidget->currentItem()->text().endsWith(".avi")){
        selectQueue.append(ui->listWidget->currentItem()->text());
        qDebug() << selectQueue;
        ui->downloadListWidget->addItem(ui->listWidget->currentItem()->text());
        ui->addBtn->setEnabled(false);
    }
    else if(ui->listWidget->currentItem()->text().endsWith(".txt")){
        QMessageBox::warning(this, "警告", "BOM表单无需手动添加", QMessageBox::Ok);
    }
    else
        QMessageBox::warning(this, "警告", "非视频类型文件无法添加", QMessageBox::Ok);
}

void fileSelectDlg::on_rmvBtn_clicked()
{
    if(ui->downloadListWidget->count() != 0){
        selectQueue.removeAt(selectQueue.indexOf(ui->downloadListWidget->currentItem()->text()));
        qDebug() << selectQueue;
        ui->downloadListWidget->takeItem(ui->downloadListWidget->row(ui->downloadListWidget->currentItem()));
    }
    emit checkFile();
}

void fileSelectDlg::on_downloadListWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
        ui->rmvBtn->setEnabled(true);
        ui->okBtn->setEnabled(true);
}

void fileSelectDlg::processCheckFile()
{
    if(ui->downloadListWidget->count() != 0)
        ui->rmvBtn->setEnabled(true);
    else {
        ui->rmvBtn->setEnabled(false);
        ui->okBtn->setEnabled(false);
    }
    if(!selectQueue.contains(ui->listWidget->currentItem()->text())){
        ui->addBtn->setEnabled(true);
    }
}

void fileSelectDlg::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    QString name = item->text();
    qDebug() << name;
    if(isDir.value(name)){
        ui->listWidget->clear();
        videoList.clear();

        if(currentPath != "/")
            currentPath += "/";

        currentPath += name;

        if(currentPath != "/")
            ui->upBtn->setEnabled(true);

        ftp->cd(toFtpEncoding(currentPath));
        ftp->list();
        ui->pathLabel->setText(currentPath);
        return ;
    }
}

void fileSelectDlg::on_listWidget_itemClicked(QListWidgetItem *item)
{
    if(isDir.value(item->text()) | selectQueue.contains(item->text()))
        ui->addBtn->setEnabled(false);
    else {
        ui->addBtn->setEnabled(true);
    }
}

void fileSelectDlg::cancelDownload()
{
    ftp->abort();
    if(file){
        file->close();
    }
}

void fileSelectDlg::setHostAndPort(QString hostAddr, unsigned short port)
{
    this->hostAddr = hostAddr;
    this->port = port;
}

//void fileSelectDlg::on_IpChangeBtn_clicked()
//{
//    IPSetDlg *ipSet = new IPSetDlg();
//    ipSet->setAttribute(Qt::WA_DeleteOnClose);
//    connect(ipSet,
//            SIGNAL(IPChanged(QString, unsigned short)),
//            this,
//            SLOT(setIPAndPort(QString, unsigned short)));
//    ipSet->exec();
//    modifyDb();
//}
